package DataStructure.linkList;

import utils.CommonUtils;

/**
 * 24. 两两交换链表中的节点 https://leetcode.cn/problems/swap-nodes-in-pairs
 */
public class SwapPairs {

    public static void main(String[] args) {
        ListNode head = CommonUtils.makeNodeList(new int[]{1, 2, 3, 4});
        new SwapPairs().swapPairs(head);
        System.out.println(head.val);
    }

    /**
     * prev.next指向p2，p1.next指向p2.nex，p2.next指向p1
     */
    public ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null) {
            return head;
        }
        ListNode prev = new ListNode(), p1 = head, p2 = head.next;
        head = p2;
        while(p1 != null && p2 != null) {
            prev.next = p2;
            prev = p1;
            p1.next = p2.next;
            p2.next = p1;
            p1 = p1.next;
            if(p1 != null) {
                p2 = p1.next;
            }
        }
        return head;
    }
}
